package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;

/**
 * @Author: QingYingYan
 * @Date: 2025-10-23 16:30
 * @Description:
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //给微信小程序发的内容
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        log.info("js_code"+userLoginDTO.getCode());
        objectObjectHashMap.put("appid", "wx4e66fc893a52d0b6");
        objectObjectHashMap.put("secret", "72f04db57500cded621ab12f4d334d6e");
        objectObjectHashMap.put("js_code", userLoginDTO.getCode());
        objectObjectHashMap.put("grant_type", "authorization_code");
//       求微信返回数据
        String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", objectObjectHashMap);
        System.out.println("返回的解析是" + s);

//        解析数据
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = (String) jsonObject.get("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }

        User openid1 = userMapper.getOpenid(openid);

        if (openid1 == null){
            User user = User.builder()
                    .openid(openid)
                    .name(openid.substring(0, 5))
                    .build();
            userMapper.addUser(user);
        }

        return openid1;
    }
}
